# -*- coding:utf-8 -*-
# @FileName : app\config.py
# @Time     : 2025/11/28
# @Author   : 天空之城
"""配置模块

此模块用于加载和管理应用的配置，包括环境变量和模型配置。
"""
import os
from dotenv import load_dotenv
from app.logger import Logger

# 加载.env文件
load_dotenv()

# 项目基础路径配置
PROJECT_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_PATH = os.path.join(PROJECT_PATH, 'data')

# 确保数据目录存在
os.makedirs(DATA_PATH, exist_ok=True)
log_dir = os.path.join(DATA_PATH, 'logs')
os.makedirs(log_dir, exist_ok=True)
LOG_FILE = os.path.join(log_dir, 'app.log')

# 创建全局日志实例
logger = Logger(log_folder_path=log_dir, log_file_name='app.log')

# Flask配置
FLASK_APP = os.getenv('FLASK_APP', 'app')
FLASK_ENV = os.getenv('FLASK_ENV', 'development')
SECRET_KEY = os.getenv('SECRET_KEY', 'your-secret-key-here')

# 数据库配置
DATABASE_URL = os.getenv('DATABASE_URL', f'sqlite:///{os.path.join(DATA_PATH, "database", "app.db")}')

# 调试数据库配置（用于app_debug.py）
DEBUG_DATABASE_URL = os.getenv('DEBUG_DATABASE_URL', DATABASE_URL)

# JWT配置
JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY', 'your-jwt-secret-key-here')
JWT_ACCESS_TOKEN_EXPIRES = int(os.getenv('JWT_ACCESS_TOKEN_EXPIRES', 3600))

# 应用配置
APP_NAME = os.getenv('APP_NAME', 'PyScreenBrain')
APP_VERSION = os.getenv('APP_VERSION', '1.0.0')
DEBUG = os.getenv('DEBUG', 'True').lower() == 'true'
TESTING = os.getenv('TESTING', 'False').lower() == 'true'

# 模型配置
DEEPSEEK_API_KEY = os.getenv('DEEPSEEK_API_KEY', '')
DEEPSEEK_MODEL = os.getenv('DEEPSEEK_MODEL', 'deepseek')

# MoDa模型配置
MODA_API_KEY = os.getenv('MODA_API_KEY', '')  # 可以是逗号分隔的多个API密钥
MODA_MODEL = os.getenv('MODA_MODEL', 'Qwen/Qwen2.5-72B-Instruct')
MODA_MAX_RETRIES_PER_KEY = int(os.getenv('MODA_MAX_RETRIES_PER_KEY', 3))

# 元景模型配置
YUANJING_APP_ID = os.getenv('YUANJING_APP_ID', '')
YUANJING_NLPT_AUTHORIZATION = os.getenv('YUANJING_NLPT_AUTHORIZATION', '')
YUANJING_APP_SECRET = os.getenv('YUANJING_APP_SECRET', '')
YUANJING_MODEL = os.getenv('YUANJING_MODEL', 'Qwen2.5-32B')
YUANJING_BASE_URL = os.getenv('YUANJING_BASE_URL', 'https://api.example.com/v1/chat/completions')
YUANJING_MAX_RETRIES = int(os.getenv('YUANJING_MAX_RETRIES', 3))

# 最大重试次数
MCP_MAX_RETRIES = int(os.getenv('MCP_MAX_RETRIES', 3))
MCP_CONNECT_TIMEOUT = int(os.getenv('MCP_CONNECT_TIMEOUT', 30))
MCP_KEEP_ALIVE_INTERVAL = int(os.getenv('MCP_KEEP_ALIVE_INTERVAL', 30))

# MCP执行器配置
MCP_SERVERS_COUNT = int(os.getenv('MCP_SERVERS_COUNT', 2))  # 执行器实例数量
MCP_SERVERS_TYPE = 'playwright-MCP'  # 仅使用playwright-MCP作为MCP工具类型

# 服务器地址配置
# 注意：AgentService 需要一个明确的 MCP_SERVER_URL
# 这里默认取列表中的第一个，或者使用默认值
MCP_SERVERS_BASE_PORT = int(os.getenv('MCP_SERVERS_BASE_PORT', 8931))
CDP_BASE_PORT = int(os.getenv('CDP_BASE_PORT', 9222))  # CDP基础端口
_default_server_url = f'http://127.0.0.1:{MCP_SERVERS_BASE_PORT}/sse'

# MCP服务器URL列表配置
MCP_SERVERS_URL = os.getenv('MCP_SERVERS_URL', '')
if not MCP_SERVERS_URL:
    # 生成MCP服务器URL列表
    MCP_SERVERS_LIST = [f'http://127.0.0.1:{MCP_SERVERS_BASE_PORT + i}/sse' for i in range(MCP_SERVERS_COUNT)]
    MCP_SERVER_URL = MCP_SERVERS_LIST[0]  # 主服务器
else:
    MCP_SERVERS_LIST = MCP_SERVERS_URL.split(',')
    MCP_SERVER_URL = MCP_SERVERS_LIST[0]
    MCP_SERVERS_COUNT = len(MCP_SERVERS_LIST)

# CDP端口列表配置
CDP_SERVERS_URL = os.getenv('CDP_SERVERS_URL', '')
if not CDP_SERVERS_URL:
    # 生成CDP服务器URL列表
    CDP_SERVERS_LIST = [f'http://127.0.0.1:{CDP_BASE_PORT + i}' for i in range(MCP_SERVERS_COUNT)]
else:
    CDP_SERVERS_LIST = CDP_SERVERS_URL.split(',')

# MCP到CDP的映射关系
# 格式：mcp_to_cdp = {'http://127.0.0.1:8931/sse': 'http://127.0.0.1:9222'}
mcp_to_cdp = {}
for i in range(min(len(MCP_SERVERS_LIST), len(CDP_SERVERS_LIST))):
    mcp_to_cdp[MCP_SERVERS_LIST[i]] = CDP_SERVERS_LIST[i]

# 环境变量覆盖映射关系
MCP_CDP_MAPPING = os.getenv('MCP_CDP_MAPPING', '')
if MCP_CDP_MAPPING:
    # 解析格式：mcp_url1:cdp_url1,mcp_url2:cdp_url2
    mappings = MCP_CDP_MAPPING.split(',')
    for mapping in mappings:
        if ':' in mapping:
            mcp_url, cdp_url = mapping.split(':', 1)
            mcp_to_cdp[mcp_url] = cdp_url

MCP_SERVERS_CHECK_INTERVAL = int(os.getenv('MCP_SERVERS_CHECK_INTERVAL', 30))  # MCP服务器检测间隔（秒）

# Agent 服务配置
AGENT_MAX_ITERATIONS = int(os.getenv('AGENT_MAX_ITERATIONS', 200))  # Agent 最大循环次数
AGENT_MAX_MESSAGES = int(os.getenv('AGENT_MAX_MESSAGES', 20))  # Agent 消息历史最大条数
AGENT_SCREENSHOT_TEXT = os.getenv('AGENT_SCREENSHOT_TEXT', '截图已捕获')  # 截图替代文本


# 兼容性配置类（供 Application Factory 使用）
class Config:
    SECRET_KEY = SECRET_KEY
    SQLALCHEMY_DATABASE_URI = DATABASE_URL
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    MCP_SERVER_URL = MCP_SERVER_URL  # 显式暴露给 Service 使用
    AGENT_MAX_ITERATIONS = AGENT_MAX_ITERATIONS
    AGENT_MAX_MESSAGES = AGENT_MAX_MESSAGES
    AGENT_SCREENSHOT_TEXT = AGENT_SCREENSHOT_TEXT
    DEBUG_DATABASE_URL = DEBUG_DATABASE_URL  # 调试数据库路径
